<?php


namespace app\controller\admin;


use app\common\model\CacheRefreshHandler;
use app\common\service\redis\PoolRedis;
use app\model\AdminDormitory;
use app\model\AdminUser;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use app\util\Tools;
use think\facade\Queue;
use think\facade\Request;
use think\Response;

class Dormitory extends Base
{
    public function index() : Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $school_name = $this->request->get('school_name', '');
        $keywords = $this->request->get('name', '');
        $sortKey = $this->request->get('sortKey', 'create_time');
        $order = $this->request->get('order', 'DESC');

        $where = [
            ['ad.is_delete', '=', 0],
            ['s.is_delete', '=', 0],
        ];

        $obj = (new AdminDormitory())->alias('ad')
            ->join('admin_school s', 'ad.school_id = s.id');
        if ($keywords) {
            array_push($where, ['ad.name', 'like', "%{$keywords}%"]);
        }
        if ($school_id > 0) {
            array_push($where, ['ad.school_id', '=', $school_id]);
        }
        if ($school_name) {
            array_push($where, ['s.name', 'like', "%{$school_name}%"]);
        }
        $listObj = $obj->where($where)
            ->field('ad.id,ad.name,ad.school_id,s.name school_name,ad.create_time')
            ->order('ad.'.$sortKey, $order)
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }
    public function add(): Response {
        $school_id = Request::post('school_id/d');
        $name = Request::post('name/s', '', 'strip_tags');
        $dormitoryCount = (new AdminDormitory())->where([
            'is_delete' => 0,
            'school_id' => $school_id,
            'name' => $name
        ])->count();
        if ($dormitoryCount > 0) {
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '宿舍楼名称已被使用');
        }
        $dormitory = new AdminDormitory();
        $dormitory->name = $name;
        $dormitory->school_id = $school_id;
        if (!$dormitory->save()) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess();
    }

    public function edit(): Response {
        $dormitory = (new AdminDormitory())->where([
            'is_delete' => 0,
            'id' => $this->request->post('id')
        ])->find();
        if (!$dormitory) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '宿舍楼未找到');
        }
        $origin = $dormitory->toArray();
        $school_id = Request::post('school_id/d');
        $name = Request::post('name/s', '', 'strip_tags');
        $dormitoryCount = (new AdminDormitory())->where([
            'is_delete' => 0,
            'school_id' => $school_id,
            'name' => $name
        ])->where('id' ,'<>', $dormitory->id)->count();
        if ($dormitoryCount > 0) {
            return $this->buildFailed(ReturnCode::DATA_EXISTS, '宿舍楼名称已被使用');
        }
        $dormitory->school_id = $school_id;
        $dormitory->name = $name;
        if (!$dormitory->save()) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        if ($origin['school_id'] != $dormitory->school_id || $origin['name'] !=  $dormitory->name) {
            CacheRefreshHandler::storeHandler('edit', $dormitory->toArray(), $origin);
        }

        return $this->buildSuccess();
    }

    public function del(): Response {
        $where['is_delete'] = 0;
        $dormitory = (new AdminDormitory())->where([
            'is_delete' => 0,
            'id' => $this->request->get('id')
        ])->find();
        if (!$dormitory) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '宿舍楼未找到');
        }
        $dormitory->is_delete = 1;
        $dormitory->save();
        CacheRefreshHandler::storeHandler('del', $dormitory->toArray());
        return $this->buildSuccess();
    }

    /**
     * @func import
     * @desc 导入宿舍楼信息
     * @return \think\Response
     * @Time: 2021/12/17 11:18
     */
    public function upload(): Response  {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('excel_file');
        $school_id = request()->post('school_id');
        if (!$school_id) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, '请选择上传的学校');
        }
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:20480|fileExt:xls,xlsx'])
                ->check([$file]);
            $fileExtendName = substr(strrchr($file->getOriginalName(), '.'), 1);
            $filePath = $file->getPathname();
            if (is_file($filePath)){
                $cols = [['1' => 'number'],['2' =>'name']];
                $data = ExcelHandle::importExcel($filePath,$cols,$fileExtendName);

                $redis = PoolRedis::instance();
                $redis->multi(\Redis::PIPELINE);

                foreach ($data as $datum) {
                    $datum['school_id'] = $school_id;
                    $redis->lPush("upload_dormitory", serialize($datum));
                }
                $redis->exec();
                Queue::push('app\task\job\UploadSyncHandlerJob@fire', [
                    'model'=> AdminDormitory::class,
                    'action' => 'upload_dormitory'
                ]);
            }
            return $this->buildSuccess();
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }

    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     * @Time: 2021/12/17 11:18
     */
    public function download(): Response  {
        $titles = [['id' => '序号'],['school_name' => '学校名称'],['name'=>'宿舍楼名称'],['create_time' => '创建时间']];

        $school_id = $this->request->get('school_id', 0);
        $school_name = $this->request->get('school_name', '');
        $keywords = $this->request->get('name', '');

        try {
            $where = [
                ['ad.is_delete', '=', 0],
                ['s.is_delete', '=', 0],
            ];

            $obj = (new AdminDormitory())->alias('ad')
                ->join('admin_school s', 'ad.school_id = s.id');
            if ($keywords) {
                array_push($where, ['ad.name', 'like', "%{$keywords}%"]);
            }
            if ($school_id > 0) {
                array_push($where, ['ad.school_id', '=', $school_id]);
            }
            if ($school_name) {
                array_push($where, ['s.name', 'like', "%{$school_name}%"]);
            }
            $listObj = $obj->where($where)
                ->field('ad.id,ad.name,ad.school_id,s.name school_name,ad.create_time')
                ->order('ad.create_time', 'DESC')
                ->select()->toArray();
            $exportData = [];
            $len = 1;
            foreach ($listObj as $datum) {
                $datum['school_name'] .= "\t";
                $newItem = array_merge(['id' => $len],$datum);
                array_push($exportData, $newItem);
                $len++;
            }
            ExcelHandle::downLoadExcel('宿舍楼信息' . date('YmdHi'), $titles, $exportData);

        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }

}